package com.webTest.Action;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.webTest.Bean.Adm;
import com.webTest.Bean.PageBean;
import com.webTest.Bean.Product;
import com.webTest.Bean.Type;
import com.webTest.Bean.UserMachine;
import com.webTest.Service.AdmService;
import com.webTest.Service.UserMachineService;
import com.webTest.tools.Md5Test;
import com.webTest.tools.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

@Controller("/userMachineAction")
public class UserMachineAction extends ActionSupport implements ServletRequestAware,ServletResponseAware {
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private UserMachine userMachine = new UserMachine();;
	private String admEmail;
	private String admPassword;
	private Integer pid;
	private String m_code;
	private String page;
	private String rows;
	private UserMachine s_userMachine;
	private String Mcodes;
	
	
	public String getMcodes() {
		return Mcodes;
	}
	public void setMcodes(String mcode) {
		Mcodes = mcode;
	}


	@Resource
	private AdmService admService;
	
	@Resource
	private UserMachineService userMachineService;
	
	public void setServletResponse(HttpServletResponse response) {
		this.response=response;
	}
	public void setServletRequest(HttpServletRequest request) {
		this.request=request;
	}
	public AdmService getAdmService() {
		return admService;
	}
	public void setAdmService(AdmService admService) {
		this.admService = admService;
	}
	public UserMachineService getUserMachineService() {
		return userMachineService;
	}
	public void setUserMachineService(UserMachineService userMachineService) {
		this.userMachineService = userMachineService;
	}
	public String getAdmEmail() {
		return admEmail;
	}
	public void setAdmEmail(String admEmail) {
		this.admEmail = admEmail;
	}
	public String getAdmPassword() {
		return admPassword;
	}
	public void setAdmPassword(String admPassword) {
		this.admPassword = admPassword;
	}
	public String getM_code() {
		return m_code;
	}
	public void setM_code(String m_code) {
		this.m_code = m_code;
	}
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}
	
	
	//用户在官网首页注册时,就在user_machine表中插入aid  在AdmAction中的register方法中实现
	
	
		//  通过用户登录的账号和密码,获得 aid 及  产品对应的产品识别码pid(手动添加) ,添加至user_machine表中
		
		
	
	//u3d 客户端传来四个参数:账号admEmail,密码admPassword,产品识别码pid,机器唯一码m_code
	
	
	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	public String getRows() {
		return rows;
	}
	public void setRows(String rows) {
		this.rows = rows;
	}
	public UserMachine getS_userMachine() {
		return s_userMachine;
	}
	public void setS_userMachine(UserMachine s_userMachine) {
		this.s_userMachine = s_userMachine;
	}
	//	http://localhost/OfficialWebsite/userMachineAction_checkU3D?admEmail=2856007760@qq.com&admPassword=1234&pid=2&m_code=34
	public String checkU3D() {
		
		System.out.println(admEmail+"====="+admPassword+"====="+pid+"======"+m_code+"======");
		
		
		String result="";
		
		Md5Test md5 = new Md5Test();
		String admPwd = md5.toMD5(admPassword);
		//先判断账号admEmail,密码admPassword 是否正确
		Adm adm = admService.get(admEmail, admPwd);
		if(null != adm) {
			
			// 正确后,获得aid, 比对pid是否正确
			Adm a = new Adm();
			Product p = new Product();
			a.setAid((adm.getAid()));
			p.setId(getPid());
			userMachine.setAdm(a);
			userMachine.setProduct(p);   
			List<UserMachine> listuserMachine2 = userMachineService.getProd(userMachine);   //同一用户买一款商品多次，在不同电脑上登录
			
			if(null != listuserMachine2) {
				for (UserMachine userMachine2 : listuserMachine2) {
					if(null == userMachine2.getMCode() || "".equals(userMachine2.getMCode())) {  //添加机器码
						userMachine2.setMCode(m_code);
						userMachineService.addM_code(userMachine2);
						result = "登录成功# ";
						break;
						
					}else {  //判断机器码是否正确
						
						if(m_code .equals(userMachine2.getMCode())) {
							result = "登录成功# ";
							break;
						}else {
							result = "登录失败#此产品已在其他机器登陆";
						}
					}
				}
				
			}else {
				result = "登录失败#您未购买此款产品";
			}
		}else {
			result = "登录失败#账号或密码错误";
		}
		System.out.println("======="+result+"=======");
		try {
			response.setContentType("text/json;charset=utf-8");
			response.getWriter().print(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}
	
	
	
	
	
	public String list() throws Exception{
		PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		List<UserMachine> list=userMachineService.usermachinelist(s_userMachine, pageBean);
		long total=userMachineService.getusermachineCount(s_userMachine);
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.setIgnoreDefaultExcludes(false);
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		jsonConfig.setExcludes(new String[] {"type"});
		JSONArray rows=JSONArray.fromObject(list, jsonConfig);
		JSONObject result=new JSONObject();
		result.put("rows", rows);
		result.put("total", total);
		ResponseUtil.write(ServletActionContext.getResponse(), result);
		return null;
	}
	
	
	
	public String save() throws Exception{
		s_userMachine.setMCode(Mcodes);
		userMachineService.upadateUserMachine(s_userMachine);
		JSONObject result=new JSONObject();
		result.put("success",true);
		ResponseUtil.write(ServletActionContext.getResponse(), result);
		return null;
	}
	
	
	public String add(){
		JSONObject result=new JSONObject();
		
		//从前台获得用户名和邮箱，需要先判断此用户是否已注册
		Adm adm = s_userMachine.getAdm();
		Adm b = userMachineService.findAdm(adm);
		if(b!=null){
			//在判断此用户购买的此商品是否已经  买过
//			int pid = s_userMachine.getProduct().getId();
//			Set<UserMachine> set = b.getUserMachines();
//			int p_id=1;
//			for (UserMachine u : set) {
//				p_id=u.getProduct().getId();
//			}
//			
//			if(pid == p_id) {
//				result.put("error", "此用户已买过此商品");
//			}else {
			
				b.setUserMachines(null);  //除去adm中的userMachine级联
				
					//如果已经注册，则进行添加user_machine的操作
				s_userMachine.setAdm(b);
		
				userMachineService.add(s_userMachine);
				result.put("success",true);
//			}
		}else{
			result.put("error", "此用户不存在");
		}
		
			try {
				ResponseUtil.write(ServletActionContext.getResponse(), result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		
		
			
		return null;
	}
	
}
